//
//  RecordSplicingViewController.m
//  BDD_TWO
//
//  Created by XTW on 2023/6/9.
//

#import "RecordSplicingViewController.h"
#import "SeeAudio.h"
#import "AVPlayerManager.h"
#import "CustomLineView.h"
#import "UIView_extension.h"
#import "EZAudioFile.h"
#import "FileManager.h"
#import "CustomAlertView.h"
#import "RecordEditSpectrumView.h"
#import "ChooseFileViewController.h"
#import "LocalRecordModel.h"

@interface RecordSplicingViewController ()<AVPlayerDelegate, UIScrollViewDelegate, UIGestureRecognizerDelegate> {
    CGFloat duration;
    CGFloat currentTime;
    CGFloat spectrumGridWidth;
    BOOL isDragging;
    NSMutableArray *dataMutArr;
    NSMutableArray *addBtnMutArr;
    NSMutableArray *itemViewMutArr;
    RecordEditSpectrumView *selectedSpectrumView;
}
@property (weak, nonatomic) IBOutlet UIImageView *bg;
@property (weak, nonatomic) IBOutlet UIScrollView *waveScrollView;
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
@property (weak, nonatomic) IBOutlet UIButton *actionBtn;
@property (weak, nonatomic) IBOutlet UILabel *timeLabel;
@property (weak, nonatomic) IBOutlet UIScrollView *itemScrollView;
@property (nonatomic, strong) CustomLineView *line;

@end

@implementation RecordSplicingViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"拼接";
    [self addBackBtn];
    [((UIButton *)[self addRigthBtn:@"完成"]) addTarget:self action:@selector(donePress) forControlEvents:UIControlEventTouchUpInside];
    
    dataMutArr = [NSMutableArray array];
    addBtnMutArr = [NSMutableArray array];
    itemViewMutArr = [NSMutableArray array];
    for (LocalRecordModel *model in self.contentArr) {
        [dataMutArr addObject:[model copy]];
    }
    
    [self initView];

    CGFloat originX = 16;
    [addBtnMutArr addObject:[self setAddButton:originX tag:0]];
    originX += 36;
    for (NSInteger i = 0; i < dataMutArr.count; i++) {
        RecordEditSpectrumView *itemView = [self setRecordEditSpectrumView:originX tag:i+1 model:[dataMutArr objectAtIndex:i]];
        [itemViewMutArr addObject:itemView];
        if (i == 0) {
            selectedSpectrumView = itemView;
            [itemView setSelected];
            [self seeAudio:itemView.model];
        }
        originX += 110;
        [addBtnMutArr addObject:[self setAddButton:originX tag:i+1]];
        originX += 36;
    }
    UIButton *lastBtn = [addBtnMutArr lastObject];
    [self.itemScrollView setContentSize:CGSizeMake(CGRectGetMaxX(lastBtn.frame) + 10, 0)];
    // Do any additional setup after loading the view from its nib.
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [AVPlayerManager manager].delegate = self;
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [[AVPlayerManager manager] pause];
    [AVPlayerManager manager].delegate = nil;
}
//添加按钮
- (UIButton *)setAddButton:(CGFloat)originX tag:(NSInteger)tag {
    UIButton *addBtn = [[UIButton alloc] initWithFrame:CGRectMake(originX, 16, 26, 26)];;
    [addBtn setImage:[UIImage imageNamed:@"edit_add"] forState:UIControlStateNormal];
    addBtn.tag = tag;
    [addBtn addTarget:self action:@selector(addItemSpectrumView:) forControlEvents:UIControlEventTouchUpInside];
    [self.itemScrollView addSubview:addBtn];
    return addBtn;
}
//添加子视图
- (RecordEditSpectrumView *)setRecordEditSpectrumView:(CGFloat)originX tag:(NSInteger)tag model:(LocalRecordModel *)model {
    RecordEditSpectrumView *itemView = [[RecordEditSpectrumView alloc] initCustomView:CGRectMake(originX, 0, 100, 85) index:tag recordModel:model];
    itemView.OnClickHandle = ^(RecordEditSpectrumView * _Nonnull itemViewEx) {
        if (itemViewEx != self->selectedSpectrumView) {
            [self->selectedSpectrumView cancelSelected];
            self->selectedSpectrumView = itemViewEx;
            [self seeAudio:itemViewEx.model];
        }
    };
    [self.itemScrollView addSubview:itemView];
    return itemView;
}
//添加按钮点击事件
- (void)addItemSpectrumView:(UIButton *)btn {
    NSLog(@"%ld", btn.tag);
    ChooseFileViewController *viewCon = [[ChooseFileViewController alloc] initWithNibName:@"ChooseFileViewController" bundle:nil];
    viewCon.type = 2;
    viewCon.ChooseFileHandle = ^(NSArray * _Nonnull arr) {
        CGFloat originX = 16 + 36 + (100 + 46)*btn.tag;
        for (NSInteger i = 0; i < arr.count; i++) {
            [self->dataMutArr insertObject:[[arr objectAtIndex:i] copy] atIndex:btn.tag+i];
            RecordEditSpectrumView *itemView = [self setRecordEditSpectrumView:originX tag:btn.tag+i+1 model:[arr objectAtIndex:i]];
            [self->itemViewMutArr insertObject:itemView atIndex:btn.tag+i];
            originX += 110;
            [self->addBtnMutArr insertObject:[self setAddButton:originX tag:i+1] atIndex:btn.tag+i+1];
            originX += 36;
        }
        [self reloadView];
    };
    CustomNavigationCoutroller *navCon = [[CustomNavigationCoutroller alloc] init];
    navCon.viewControllers = @[viewCon];
    navCon.modalPresentationStyle = UIModalPresentationFullScreen;
    [self.navigationController presentViewController:navCon animated:YES completion:nil];
}

//刷新一下子视图内容
- (void)reloadView {
    for (NSInteger i = 0; i < itemViewMutArr.count; i++) {
        RecordEditSpectrumView *itemView = [itemViewMutArr objectAtIndex:i];
        [itemView refreshTag:i+1];
        [itemView setFrame:CGRectMake(6 + 46*(i+1) + 100*i, 0, 100, 85)];
    }
    for (NSInteger i = 1; i < addBtnMutArr.count; i++) {
        UIButton *btn = [addBtnMutArr objectAtIndex:i];
        btn.tag = i;
        [btn setFrame:CGRectMake(6 + (46+100)*i +10, 16, 26, 26)];
    }
    UIButton *lastBtn = [addBtnMutArr lastObject];
    [self.itemScrollView setContentSize:CGSizeMake(CGRectGetMaxX(lastBtn.frame) + 10, 0)];
}

- (void)donePress {
    if (self.ReloadHandle) {
        self.ReloadHandle(dataMutArr);
    }
    [self goBackAction];
}


- (IBAction)deletePress {
    if (itemViewMutArr.count == 1) {
        [self showHUDAlert:@"至少保留一段音频"];
        return;
    }
    CustomAlertView *alertView = [[CustomAlertView alloc] initItem:@"确定要删除该音频？" withButtons:[NSArray arrayWithObjects:@"取消", @"确定", nil]];
    alertView.SureHandle = ^{
        NSInteger index = [self->itemViewMutArr indexOfObject:self->selectedSpectrumView];
        [[self->itemViewMutArr objectAtIndex:index] removeFromSuperview];
        [[self->addBtnMutArr objectAtIndex:index+1] removeFromSuperview];
        [self->itemViewMutArr removeObjectAtIndex:index];
        [self->addBtnMutArr removeObjectAtIndex:index+1];
        [self->dataMutArr removeObjectAtIndex:index];
        
        self->selectedSpectrumView = [self->itemViewMutArr firstObject];
        [self->selectedSpectrumView setSelected];
        [self seeAudio:self->selectedSpectrumView.model];
        
        [self reloadView];
    };
    [alertView backgroundClickDisable];
    [alertView show];
}

- (IBAction)actionPress {
    self.actionBtn.selected = !self.actionBtn.selected;
    if (!self.actionBtn.selected) {
        [[AVPlayerManager manager] pause];
    } else {
        [[AVPlayerManager manager] play];
    }
}

- (void)seeAudio:(LocalRecordModel *)model {
    NSURL *url = nil;
    if (model.needSaveUrl) {
        url = model.needSaveUrl;
    } else {
        url = [NSURL fileURLWithPath:[[FileManager sharedManager] getLocalFilePath:selectedSpectrumView.model.fileName]];
    }
    [[AVPlayerManager manager] pause];
    [self trackPlayDidEnd];
    [self.waveScrollView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    [[AVPlayerManager manager] setAVPlayerURL:url];
    AVURLAsset  *asset = [[AVURLAsset alloc] initWithURL:url options:nil];
    duration = CMTimeGetSeconds(asset.duration);
    __weak __typeof(self) weakSelf = self;
    [SeeAudio renderPNGAudioPictogramLogForAsset:asset done:^(UIImage *spectrumImage,UIImage *scaleImage,NSInteger imageWidth) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self hideHudAlert];
            [weakSelf.waveScrollView setContentSize:CGSizeMake(imageWidth, 0)];
            UIImageView *imgv = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, imageWidth, 280)];
            imgv.image = spectrumImage;
            [weakSelf.waveScrollView addSubview:imgv];
            UIImageView *scaleImgv = [[UIImageView alloc] initWithFrame:CGRectMake(0, 280, imageWidth, 30)];
            scaleImgv.image = scaleImage;
            [weakSelf.waveScrollView addSubview:scaleImgv];
            
        });
    }];
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    isDragging = YES;
    [[AVPlayerManager manager] pause];
    self.actionBtn.selected = NO;
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    isDragging = NO;
    [[AVPlayerManager manager] seekToTimeInterval:currentTime];

//    [[AVPlayerManager manager] play];
//    self.actionBtn.selected = YES;
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    [[AVPlayerManager manager] seekToTimeInterval:currentTime];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (self.waveScrollView == scrollView) {
        currentTime = (scrollView.contentOffset.x/(scrollView.contentSize.width-SCREEN_WIDTH_DEVICE))*duration;
        if (currentTime > duration) {
            currentTime = duration;
        } else if (currentTime <= 0) {
            currentTime = 0;
        }
        int currentMin  = (int)currentTime / 60;
        int currentSecond  = (int)currentTime % 60;
        int millisecond = (currentTime - currentSecond)*100 - currentMin*60*100;
        NSString *currentTime1 = [NSString stringWithFormat:@"%.2d:%.2d.%02d",currentMin,currentSecond, millisecond];
        self.timeLabel.text = currentTime1;
    }
}

#pragma mark ---AVPlayerDelegate---
- (void)timeRunAndTime:(double)runTime andValue:(NSString *)value andScale:(CGFloat)scale {
    currentTime = runTime;
    self.timeLabel.text = value;
    if ([AVPlayerManager manager].isPlaying) {
        CGFloat pointX = (self.waveScrollView.contentSize.width-SCREEN_WIDTH_DEVICE)*scale;
        if (pointX < self.waveScrollView.contentOffset.x) {
            pointX = self.waveScrollView.contentOffset.x;
        }
        [UIView animateWithDuration:0.1 animations:^{
            [self.waveScrollView setContentOffset:CGPointMake(pointX, 0) animated:NO];
        }];
    }
}

- (void)trackPlayDidEnd {
    self.actionBtn.selected = NO;
    [self.waveScrollView setContentOffset:CGPointMake(0, 0) animated:YES];
}


- (void)initView {
    [self.bg setFrame:CGRectMake(0, IS_iPhoneX_Top + NavBarHeight + 280, SCREEN_WIDTH_DEVICE, SCREEN_HEIGHT_DEVICE - (IS_iPhoneX_Top + NavBarHeight + 280))];
    [self.scrollView setFrame:CGRectMake(0, IS_iPhoneX_Top + NavBarHeight + 310, SCREEN_WIDTH_DEVICE, SCREEN_HEIGHT_DEVICE - IS_iPhoneX_Bottom - IS_iPhoneX_Top - NavBarHeight - 50 - 310)];
    [self.scrollView setContentSize:CGSizeMake(0, 300)];
    [self.waveScrollView setFrame:CGRectMake(0, IS_iPhoneX_Top + NavBarHeight, SCREEN_WIDTH_DEVICE, 310)];
    [self.view addSubview:self.line];

}

- (CustomLineView *)line {
    if (!_line) {
        _line = [[CustomLineView alloc] initCustomView:CGRectMake((SCREEN_WIDTH_DEVICE-3)/2.0, IS_iPhoneX_Top + NavBarHeight, 3, 280)];
    }
    return _line;
}
@end
